<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="学号" prop="studentNum">
        <el-input
            v-model="queryParams.studentNum"
            placeholder="请输入学号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="硕士/博士" prop="shuoshiboshi">
        <el-select v-model="queryParams.shuoshiboshi" placeholder="请选择硕士还是博士" filterable>
          <el-option
              v-for="dict in sys_shuobo"
              :key="dict.id"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8 button-row">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"

        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"

        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"

        >删除</el-button>
      </el-col>
      <!-- 使用更宽的列来容纳长按钮 -->
      <el-col :span="3">
        <el-button
            type="primary"
            plain
            icon="refresh"
            @click="handleInsert"
            :loading="importLoading"
        >批量导入硕士到学籍信息中</el-button>
      </el-col>
      <!-- 新增的批量导入博士到学籍信息按钮 -->
      <el-col :span="2.5">
        <el-button
            type="primary"
            plain
            icon="Upload"
            @click="handlePhdImportxueji"
            :loading="importLoading"
        >批量导入博士到学籍信息中</el-button>
      </el-col>
      <!-- 新增博士导入按钮 -->
      <el-col :span="2.3">
        <el-button
            type="primary"
            plain
            icon="refresh"
            @click="handlePhdImport"
            :loading="importLoading"
        >批量导入博士到报道信息中</el-button>
      </el-col>
      <el-col :span="2.3">
        <el-button
            type="info"
            plain
            icon="Refresh"
            @click="updateFromEnrollment"
        >导入硕士信息到当年报道信息中</el-button>
      </el-col>
      <el-col :span="2">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>



    <!-- 导入进度弹窗 -->
    <el-dialog
        v-model="showProgressDialog"
        title="数据导入进度"
        width="600px"
        :close-on-click-modal="false"
        :show-close="false"
        :modal-append-to-body="true"
        :append-to-body="true"
    >
      <div v-if="!importCompleted" class="progress-container">
        <el-progress
            :percentage="progressPercent"
            :status="progressStatus"
            :text-inside="true"
            stroke-width="12"
            style="margin-bottom: 30px; height: 30px;"
        >
          <template #default="{ percentage }">
            <span style="font-size: 16px; font-weight: bold;">{{ progressText }}</span>
          </template>
        </el-progress>
        <p class="progress-info" style="font-size: 14px;">{{ progressDetail }}</p>
      </div>

      <div v-else class="result-container">
        <div class="result-icon" :class="importSuccess ? 'success' : 'error'">
          <i class="el-icon-check" v-if="importSuccess"></i>
          <i class="el-icon-error" v-else></i>
        </div>
        <h3 class="result-title">{{ importSuccess ? '导入成功' : '导入失败' }}</h3>
        <div class="result-details" v-if="importSuccess">
          <p>总记录数: {{ importStats.total || 0 }}</p>
          <p>成功导入: {{ importStats.successCount || 0 }}</p>
          <p>失败记录: {{ importStats.failureCount || 0 }}</p>
          <p v-if="importStats.successCount === 0 && importStats.total > 0" class="special-message">
            提示: 可导入学生已经全部入库
          </p>
          <p v-if="importStats.failureCount > 0" class="failure-message">
            失败原因: {{ importStats.errorMsg || '未知错误' }}
          </p>
        </div>
        <div class="result-details" v-else>
          <p class="failure-message">{{ importStats.errorMsg || '导入过程中发生未知错误' }}</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer" v-if="importCompleted">
          <el-button type="primary" @click="closeProgressDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-table v-loading="loading" :data="baodaoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="studentName" />
      <el-table-column label="学号" align="center" prop="studentNum" />
      <el-table-column label="学院" align="center" prop="studentXy" />
      <el-table-column label="专业" align="center" prop="studentZy" />
      <el-table-column label="身份证" align="center" prop="idcard">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handlePreview(scope.row.idcard)"
          >预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="学位证" align="center" prop="xwz" >
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handlePreview(scope.row.xwz)"
          >预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="毕业证" align="center" prop="byz" >
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handlePreview(scope.row.byz)"
          >预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="缴费记录" align="center" prop="jfjl" >
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handlePreview(scope.row.jfjl)"
          >预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="其他材料" align="center" prop="qita" >
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handlePreview(scope.row.qita)"
          >预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="硕士/博士" align="center" prop="shuoshiboshi" >
        <template #default="scope">
          {{ sys_shuobo.find(item => item.value === scope.row.shuoshiboshi)?.label || scope.row.shuoshiboshi }}
        </template>
      </el-table-column>
      <el-table-column label="报道状态" align="center" prop="typeStatus" >
        <template #default="scope">
          {{ rxbdzt.find(item => item.value === scope.row.typeStatus)?.label || scope.row.typeStatus }}
        </template>
      </el-table-column>
      <el-table-column label="未通过或未报到原因" align="center" prop="question" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleSingleInsert(scope.row)" >导入学生数据库</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <el-dialog v-model="previewDialogVisible" title="文件预览" width="60%">
      <template v-if="previewType === 'pdf'">
        <iframe
            :src="previewUrl"
            width="100%"
            height="600px"
            frameborder="0"
        />
      </template>
      <template v-else>
        <img :src="previewUrl" alt="预览图片"
             style="max-width: 100%; max-height: 600px; display: block; margin: 0 auto;" />
      </template>
    </el-dialog>

    <!-- 添加或修改新生报到对话框 -->
    <!-- 添加或修改新生报到对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="baodaoRef" :model="form" :rules="rules" label-width="150px">
        <!-- 第一行：姓名 + 学号 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="studentName">
              <el-input
                  v-model="form.studentName"
                  placeholder="请输入姓名"
                  :disabled="!!form.id"
                  style="max-width: 300px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学号" prop="studentNum">
              <el-input
                  v-model="form.studentNum"
                  placeholder="请输入学号"
                  :disabled="!!form.id"
                  style="max-width: 300px;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：学院 + 专业 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="学院" prop="studentXy">
              <el-input
                  v-model="form.studentXy"
                  placeholder="请输入学院"
                  :disabled="!!form.id"
                  style="max-width: 300px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="studentZy">
              <el-input
                  v-model="form.studentZy"
                  placeholder="请输入专业"
                  :disabled="!!form.id"
                  style="max-width: 300px;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：身份证 + 学位证 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idcard">
              <file-upload
                  v-model="form.idcard"
                  :file-type="['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']"
                  :file-size="1024"
                  :limit="1"
                  style="max-width: 300px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学位证" prop="xwz">
              <file-upload
                  v-model="form.xwz"
                  :file-type="['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']"
                  :file-size="1024"
                  :limit="1"
                  style="max-width: 300px;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：毕业证 + 缴费记录 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="毕业证" prop="byz">
              <file-upload
                  v-model="form.byz"
                  :file-type="['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']"
                  :file-size="1024"
                  :limit="1"
                  style="max-width: 300px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缴费记录" prop="jfjl">
              <file-upload
                  v-model="form.jfjl"
                  :file-type="['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']"
                  :file-size="1024"
                  :limit="1"
                  style="max-width: 300px;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：其他材料 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="其他材料" prop="qita">
              <file-upload
                  v-model="form.qita"
                  :file-type="['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']"
                  :file-size="1024"
                  :limit="5"
                  style="max-width: 700px;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行：硕士/博士 + 报道状态 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="硕士/博士" prop="shuoshiboshi">
              <el-select
                  v-model="form.shuoshiboshi"
                  placeholder="请选择硕士还是博士"
                  filterable
                  style="max-width: 300px;"
              >
                <el-option
                    v-for="dict in sys_shuobo"
                    :key="dict.id"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报道状态" prop="typeStatus">
              <el-select
                  v-model="form.typeStatus"
                  placeholder="请选择报到状态"
                  filterable
                  style="max-width: 300px;"
              >
                <el-option
                    v-for="dict in rxbdzt"
                    :key="dict.id"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第七行：未通过或未报到原因 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="未通过或未报到原因" prop="question">
              <el-input
                  v-model="form.question"
                  type="textarea"
                  placeholder="请输入内容"
                  style="max-width: 700px;"
                  rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-button
        class="scroll-to-bottom-btn"
        type="primary"
        icon="ArrowDown"
        circle
        @click="scrollToBottom"
    />
  </div>
</template>

<script setup name="Baodao">
import {
  listBaodao,
  getBaodao,
  delBaodao,
  addBaodao,
  updateBaodao,
  importAllStudents,
  importStudents,
  startImport,
  getImportProgress,
  startBoShiImport,
  importAllBoShiStudents,
  getImportBoShiProgress
} from "@/api/student/baodao";
import { listDept } from "@/api/system/dept";
import { listRole } from "@/api/system/role";
import { addUser } from "@/api/system/user";
import { listCollege } from "@/api/college/college";
import { selectStudentBaoDaoList } from "@/api/student/allList";
const { proxy } = getCurrentInstance();
const { rxbdzt,sys_shuobo } = proxy.useDict('rxbdzt','sys_shuobo');
import downloads from "@/plugins/download.js"

// 导入进度相关变量
const importLoading = ref(false);
const showProgressDialog = ref(false); // 控制进度弹窗显示
const progressPercent = ref(0);
const progressText = ref('准备中...');
const progressDetail = ref('初始化导入任务...');
const progressStatus = ref('');
const importCompleted = ref(false);
const importSuccess = ref(false);
const importStats = ref({
  total: 0,
  successCount: 0,
  failureCount: 0,
  errorMsg: ''
});
let progressInterval = null;

const previewDialogVisible = ref(false);
const previewUrl = ref("");
const previewType = ref("");
const baodaoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentName: null,
    studentNum: null,
    xyCode: null,
    studentXy: null,
    studentZy: null,
    idcard: null,
    xwz: null,
    byz: null,
    jfjl: null,
    qita: null,
    shuoshiboshi: null,
    typeStatus: null,
    question: null
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询新生报到列表 */
function getList() {
  loading.value = true;
  selectStudentBaoDaoList(queryParams.value).then(response => {
    baodaoList.value = response.rows;
    console.log('baodaoList======', baodaoList.value)
    total.value = response.total;
    loading.value = false;
  });
}

// 或者创建一个映射对象以便多次使用
async function createCollegeCodeToNameMap() {
  try {
    const response = await listCollege({});
    if (response && response.rows) {
      const map = {};
      response.rows.forEach(college => {
        if (college.collegeCode) {
          map[college.collegeCode] = college.collegeName;
        }
      });
      return map;
    }
    return {};
  } catch (error) {
    return {};
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    studentName: null,
    studentNum: null,
    xyCode: null,
    studentXy: null,
    studentZy: null,
    idcard: null,
    xwz: null,
    byz: null,
    jfjl: null,
    qita: null,
    shuoshiboshi: null,
    typeStatus: null,
    question: null
  };
  proxy.resetForm("baodaoRef");
}

// 跳转到底部
function scrollToBottom() {
  window.scrollTo({
    top: document.documentElement.scrollHeight,
    behavior: 'smooth'
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加新生报到";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBaodao(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改新生报到";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["baodaoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBaodao(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBaodao(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除新生报到编号为"' + _ids + '"的数据项？').then(function () {
    return delBaodao(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 批量导入到学籍信息（只导入boshishuoshi=1的硕士） */
async function handleInsert() {
  proxy.$modal.confirm('是否确认导入所有硕士（boshishuoshi=1）到学籍数据库？').then(async () => {
    // 初始化进度弹窗
    initProgressDialog();

    try {
      // 启动异步导入
      const { data: batchNo } = await startImport();

      // 清除可能存在的旧定时器
      if (progressInterval) {
        clearInterval(progressInterval);
      }

      // 轮询查询进度
      progressInterval = setInterval(async () => {
        try {
          const { data: progress } = await getImportProgress(batchNo);

          // 更新进度信息
          progressPercent.value = progress.progress;

          // 更新显示文本
          if (progress.status === '处理中') {
            progressText.value = `正在导入硕士: ${progress.successCount}/${progress.total} 条`;
            progressDetail.value = `已完成 ${progress.progress}%，请稍候...`;
            progressStatus.value = '';
          } else if (progress.status === '完成') {
            // 导入完成，更新统计信息
            completeImport(true, {
              total: progress.total,
              successCount: progress.successCount,
              failureCount: progress.total - progress.successCount,
              errorMsg: ''
            });

            // 导入完成后，开始创建用户
            await createUsersAfterImport();
          } else if (progress.status === '失败') {
            // 导入失败
            completeImport(false, {
              errorMsg: progress.errorMsg || '导入过程中发生错误'
            });
          }

          // 超时处理（30分钟）
          const elapsedTime = (new Date().getTime() - startTime) / 1000 / 60;
          if (elapsedTime > 30) {
            throw new Error('导入超时');
          }
        } catch (error) {
          clearInterval(progressInterval);
          completeImport(false, {
            errorMsg: error.message || '获取导入进度失败'
          });
        }
      }, 1000);

      // 记录开始时间用于超时判断
      const startTime = new Date().getTime();

    } catch (error) {
      completeImport(false, {
        errorMsg: error.msg || '启动导入失败'
      });
    }
  }).catch(() => {
    importLoading.value = false;
  });
}

/** 新增：批量导入博士信息到学籍库（只导入boshishuoshi=2的博士） */
async function handlePhdImportxueji() {
  proxy.$modal.confirm('是否确认导入所有博士（boshishuoshi=2）到学籍数据库？').then(async () => {
    // 初始化进度弹窗
    initProgressDialog();

    try {
      // 启动博士异步导入
      const { data: batchNo } = await startBoShiImport();
      // 清除可能存在的旧定时器
      if (progressInterval) {
        clearInterval(progressInterval);
      }

      // 轮询查询博士导入进度
      progressInterval = setInterval(async () => {
        try {
          const { data: progress } = await getImportBoShiProgress(batchNo);
          // 更新进度信息
          progressPercent.value = progress.progress;
          // 更新显示文本，增加"博士"标识
          if (progress.status === '处理中') {
            progressText.value = `正在导入博士: ${progress.successCount}/${progress.total} 条`;
            progressDetail.value = `已完成 ${progress.progress}%，请稍候...`;
            progressStatus.value = '';
          } else if (progress.status === '完成') {
            // 导入完成，更新统计信息
            completeImport(true, {
              total: progress.total,
              successCount: progress.successCount,
              failureCount: progress.total - progress.successCount,
              errorMsg: ''
            });

            // 导入完成后，为博士创建用户
            await createPhdUsersAfterImport();
          } else if (progress.status === '失败') {
            // 导入失败
            completeImport(false, {
              errorMsg: progress.errorMsg || '博士信息导入过程中发生错误'
            });
          }

          // 超时处理（30分钟）
          const elapsedTime = (new Date().getTime() - startTime) / 1000 / 60;
          if (elapsedTime > 30) {
            throw new Error('博士信息导入超时');
          }
        } catch (error) {
          clearInterval(progressInterval);
          completeImport(false, {
            errorMsg: error.message || '获取博士导入进度失败'
          });
        }
      }, 1000);

      // 记录开始时间用于超时判断
      const startTime = new Date().getTime();

    } catch (error) {
      completeImport(false, {
        errorMsg: error.msg || '启动博士信息导入失败'
      });

    }
  }).catch(() => {
    importLoading.value = false;
  });
}

/** 导入完成后创建普通学生用户（硕士） */
async function createUsersAfterImport() {
  try {
    // 获取所有硕士学生数据（筛选出boshishuoshi=1的记录）
    let allStudents = [];
    let pageNum = 1;
    const pageSize = 100;
    let hasMore = true;

    // 分页获取所有数据并筛选硕士
    while (hasMore) {
      const response = await listBaodao({
        pageNum: pageNum,
        pageSize: pageSize,
        shuoshiboshi: '1' // 只筛选硕士
      });

      allStudents = allStudents.concat(response.rows);

      // 判断是否还有更多数据
      if (response.rows.length < pageSize || allStudents.length >= response.total) {
        hasMore = false;
      }

      pageNum++;
    }

    const students = allStudents;

    // 重新初始化进度条用于用户创建
    initProgressDialog();
    progressText.value = '准备创建硕士用户...';
    progressDetail.value = `共需创建 ${students.length} 个硕士用户`;
    importStats.value = {
      total: students.length,
      successCount: 0,
      failureCount: 0,
      errorMsg: '',
      failedStudents: [] // 添加失败学生列表
    };

    // 为每个硕士创建用户账户
    let successCount = 0;
    let failureCount = 0;
    let failedStudents = []; // 记录失败的学生

    // 预先获取部门和角色信息
    const deptResponse = await listDept();
    const roleResponse = await listRole({ roleName: '学生' });

    for (let i = 0; i < students.length; i++) {
      const student = students[i];

      try {
        // 更新进度
        progressPercent.value = Math.round(((i + 1) / students.length) * 100);
        progressText.value = `正在创建硕士用户: ${i + 1}/${students.length}`;
        progressDetail.value = `当前处理: ${student.studentName} (${student.studentNum})`;

        let deptId = null;

        if (deptResponse.data && deptResponse.data.length > 0) {
          // 根据学生信息中的学院字段找到对应的部门
          const collegeDept = deptResponse.data.find(dept => dept.deptName === student.studentXy);

          if (collegeDept) {
            // 查找学生对应的部门
            const studentDept = deptResponse.data.find(dept =>
                dept.ancestors.includes(collegeDept.deptId) &&
                dept.deptName === '学生'
            );

            deptId =  studentDept.deptId ;
          }
        }

        if (!deptId) {
          failureCount++;
          failedStudents.push({
            name: student.studentName,
            num: student.studentNum,
            reason: '未找到对应部门'
          });
          continue;
        }

        let roleId = null;

        if (roleResponse.rows && roleResponse.rows.length > 0) {
          const matchedRole = roleResponse.rows.find(role => role.roleName === '学生');
          if (matchedRole) {
            roleId = matchedRole.roleId;
          }
        }

        if (!roleId) {
          failureCount++;
          failedStudents.push({
            name: student.studentName,
            num: student.studentNum,
            reason: '未找到学生角色'
          });
          continue;
        }

        // 创建用户
        const userData = {
          userName: student.studentNum,
          nickName: student.studentName,
          password: '123456',
          deptId: deptId,
          roleIds: [roleId]
        };

        await addUser(userData);
        successCount++;

      } catch (error) {
        failureCount++;
        failedStudents.push({
          name: student.studentName,
          num: student.studentNum,
          reason: error.message || '创建用户时发生错误'
        });
      }

      // 更新统计信息
      importStats.value.successCount = successCount;
      importStats.value.failureCount = failureCount;
      importStats.value.failedStudents = failedStudents; // 更新失败学生列表
    }

    // 完成用户创建
    progressPercent.value = 100;
    progressText.value = '硕士用户创建完成';
    progressDetail.value = `成功: ${successCount}, 失败: ${failureCount}`;

    if (failureCount === 0) {
      progressStatus.value = 'success';
      proxy.$modal.msgSuccess("硕士批量导入和用户创建完成");
    } else {
      progressStatus.value = 'warning';
      // 显示失败学生信息
      let failMessage = `用户创建完成，成功: ${successCount}，失败: ${failureCount}`;
      if (failedStudents.length > 0) {
        const failedList = failedStudents.map(s => `${s.name}(${s.num}): ${s.reason}`).join('\n');
        failMessage += `\n\n失败学生列表:\n${failedList}`;
      }
      proxy.$modal.msgWarning(failMessage);
    }

    // 标记导入完成
    importCompleted.value = true;
    importSuccess.value = failureCount === 0;
    // 保存失败学生信息用于弹窗显示
    importStats.value.failedStudents = failedStudents;

  } catch (error) {
    progressStatus.value = 'exception';
    progressText.value = '硕士用户创建失败';
    progressDetail.value = error.message || "未知错误";
    importCompleted.value = true;
    importSuccess.value = false;
    proxy.$modal.msgError("批量硕士用户创建失败: " + (error.message || "未知错误"));
  }
}

/** 新增：博士信息导入完成后创建用户（只处理boshishuoshi=2的记录） */
async function createPhdUsersAfterImport() {
  try {
    // 获取所有博士学生数据（筛选出boshishuoshi=2的记录）
    let allPhdStudents = [];
    let pageNum = 1;
    const pageSize = 100;
    let hasMore = true;

    // 分页获取并筛选博士数据
    while (hasMore) {
      const response = await listBaodao({
        pageNum: pageNum,
        pageSize: pageSize,
        shuoshiboshi: '2',// 只筛选博士
        typeStatus:'1'//报道状态为
      });
      allPhdStudents = allPhdStudents.concat(response.rows);

      if (response.rows.length < pageSize || allPhdStudents.length >= response.total) {
        hasMore = false;
      }

      pageNum++;
    }

    const phdStudents = allPhdStudents;

    // 重新初始化进度条用于用户创建
    initProgressDialog();
    progressText.value = '准备创建博士用户...';
    progressDetail.value = `共需创建 ${phdStudents.length} 个博士用户`;
    importStats.value = {
      total: phdStudents.length,
      successCount: 0,
      failureCount: 0,
      errorMsg: ''
    };

    // 为每个博士创建用户账户
    let successCount = 0;
    let failureCount = 0;

    // 预先获取部门和角色信息
    const deptResponse = await listDept();
    // 获取博士角色
    const roleResponse = await listRole({ roleName: '博士' });


    for (let i = 0; i < phdStudents.length; i++) {
      const student = phdStudents[i];

      try {
        // 更新进度
        progressPercent.value = Math.round(((i + 1) / phdStudents.length) * 100);
        progressText.value = `正在创建博士用户: ${i + 1}/${phdStudents.length}`;
        progressDetail.value = `当前处理: ${student.studentName} (${student.studentNum})`;

        let deptId = null;

        if (deptResponse.data && deptResponse.data.length > 0) {
          // 根据学生信息中的学院字段找到对应的部门
          const collegeDept = deptResponse.data.find(dept => dept.deptName === student.studentXy);
          if (collegeDept) {
            // 查找博士对应的部门
            const phdDept = deptResponse.data.find(dept =>
                dept.ancestors.includes(collegeDept.deptId) &&
                dept.deptName === '学生'
            );

            deptId =phdDept.deptId;
          }
        }

        if (!deptId) {
          failureCount++;
          continue;
        }

        let roleId = null;

        if (roleResponse.rows && roleResponse.rows.length > 0) {
          // 找到博士角色
          const matchedRole = roleResponse.rows.find(role => role.roleName === '博士');
          if (matchedRole) {
            roleId = matchedRole.roleId;
          }
        }

        if (!roleId) {
          failureCount++;
          continue;
        }

        // 创建博士用户
        const userData = {
          userName: student.studentNum,
          nickName: student.studentName,
          password: '123456',
          deptId: deptId,
          roleIds: [roleId]
        };

        await addUser(userData);
        successCount++;

      } catch (error) {
        failureCount++;
      }

      // 更新统计信息
      importStats.value.successCount = successCount;
      importStats.value.failureCount = failureCount;
    }

    // 完成用户创建
    progressPercent.value = 100;
    progressText.value = '博士用户创建完成';
    progressDetail.value = `成功: ${successCount}, 失败: ${failureCount}`;

    if (failureCount === 0) {
      progressStatus.value = 'success';
      proxy.$modal.msgSuccess("博士信息批量导入和用户创建完成");
    } else {
      progressStatus.value = 'warning';
      proxy.$modal.msgWarning(`博士用户创建完成，成功: ${successCount}，失败: ${failureCount}`);
    }

    // 标记导入完成
    importCompleted.value = true;
    importSuccess.value = failureCount === 0;

  } catch (error) {
    progressStatus.value = 'exception';
    progressText.value = '博士用户创建失败';
    progressDetail.value = error.message || "未知错误";
    importCompleted.value = true;
    importSuccess.value = false;
    proxy.$modal.msgError("批量博士用户创建失败: " + (error.message || "未知错误"));
  }
}

/** 初始化进度弹窗 */
function initProgressDialog() {
  importLoading.value = true;
  showProgressDialog.value = true;
  importCompleted.value = false;
  importSuccess.value = false;
  progressPercent.value = 0;
  progressText.value = '准备中...';
  progressDetail.value = '初始化导入任务...';
  progressStatus.value = '';
  importStats.value = {
    total: 0,
    successCount: 0,
    failureCount: 0,
    errorMsg: ''
  };
}

/** 完成导入，更新结果 */
function completeImport(success, stats) {
  clearInterval(progressInterval);
  importLoading.value = false;
  importCompleted.value = true;
  importSuccess.value = success;
  importStats.value = { ...importStats.value, ...stats };

  // 显示提示消息
  if (success) {
    progressStatus.value = 'success';
    // 处理0条导入的情况
    if (stats.successCount === 0 && stats.total > 0) {
      progressText.value = '导入完成';
      progressDetail.value = '所有可导入学生已全部入库';
    } else {
      progressText.value = '导入完成';
      progressDetail.value = `共成功导入 ${stats.successCount} 条数据`;
    }
  } else {
    progressStatus.value = 'exception';
    progressText.value = '导入失败';
    progressDetail.value = stats.errorMsg || '导入过程中发生错误';
  }
}


/** 关闭进度弹窗 */
function closeProgressDialog() {
  showProgressDialog.value = false;
  importLoading.value = false; // 重置导入按钮的加载状态
  if (importSuccess.value) {
    getList(); // 刷新列表
  }
}


/** 单个导入到学籍信息 */
async function handleSingleInsert(row) {
  proxy.$modal.confirm(`是否确认将学生【${row.studentName}(${row.studentNum})】导入到数据库？`).then(function () {
    return importStudents({studentNum: row.studentNum});
  }).then((response) => {
    getList();
    // 处理单个导入0条的情况
    if (response.data === 0) {
      proxy.$modal.msgSuccess(`${row.studentName}已在学籍库中，无需重复导入`);
    } else {
      proxy.$modal.msgSuccess(`${response.msg}，共导入 ${response.data} 条数据`);
    }
  }).catch((error) => {
    if (error && error.msg) {
      proxy.$modal.msgError(error.msg);
    } else {
      proxy.$modal.msgError("导入失败，请稍后重试");
    }
  });

  // 显示加载状态
  const loading = proxy.$loading({
    lock: true,
    text: '正在导入用户信息...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    // 获取部门数据
    const deptResponse = await listDept();
    let deptId = null;

    if (deptResponse.data && deptResponse.data.length > 0) {



      // 1. 根据学生信息中的学院字段找到对应的部门
      const collegeDept = deptResponse.data.find(dept => dept.deptName === row.studentXy);

      if (collegeDept) {
        // 根据学生类型选择对应的部门
        const targetDept = deptResponse.data.find(dept => dept.ancestors.includes(collegeDept.deptId) && dept.deptName === '学生');
        deptId =  targetDept.deptId ;
      }
    }

    if (!deptId) {
      throw new Error(`未找到对应的部门: ${row.studentXy}`);
    }

    // 根据学生类型选择对应的角色
    const roleType = row.shuoshiboshi === '2' ? '博士' : '学生';
    const roleResponse = await listRole({roleName: roleType});
    let roleId = null;

    if (roleResponse.rows && roleResponse.rows.length > 0) {
      const matchedRole = roleResponse.rows.find(role => role.roleName === roleType);
      if (matchedRole) {
        roleId = matchedRole.roleId;
      }
    }

    if (!roleId) {
      throw new Error(`未找到${roleType}角色`);
    }

    // 创建用户
    const userData = {
      userName: row.studentNum,
      nickName: row.studentName,
      password: '123456',
      deptId: deptId,
      roleIds: [roleId]
    };

    await addUser(userData);
    loading.close();

    // 显示成功消息
    proxy.$modal.msgSuccess(`${row.studentName} 用户创建成功`);
    getList();

  } catch (error) {
    // 关闭加载状态
    loading.close();

    // 显示错误消息
    proxy.$modal.msgError(error.message || '导入用户失败，请稍后重试');
  }
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('student/baodao/export', {
    ...queryParams.value
  }, `baodao_${new Date().getTime()}.xlsx`)
}

/** 从招生数据更新报到学生 */
function updateFromEnrollment() {
  proxy.$modal.confirm('确定要从招生数据更新报到学生吗？此操作将同步招生数据到报到表。').then(() => {
    // 显示加载状态
    const loadingInstance = proxy.$loading({
      lock: true,
      text: '正在更新数据，请稍候...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 调用批量导入API
    importAllStudents().then(response => {
      proxy.$modal.msgSuccess("更新成功");
      getList();
    }).catch(error => {
      proxy.$modal.msgError("更新失败，请检查控制台");
    }).finally(() => {
      loadingInstance.close();
    });
  });
}

function handlePreview(resourcePath) {
  if (!resourcePath) {
    proxy.$modal.msgWarning("暂无可预览的文件");
    return;
  }

  downloads.preview(resourcePath, (blobUrl, fileType) => {
    previewUrl.value = blobUrl;
    previewType.value = fileType;
    previewDialogVisible.value = true;
  });
}
function handlePhdImport() {
  proxy.$modal.confirm('确定要批量导入博士信息吗？').then(() => {
    // 显示加载状态
    const loading = proxy.$loading({
      lock: true,
      text: '正在导入博士信息...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    importAllBoShiStudents()
        .then(response => {
          loading.close();
          // 解析返回消息中的成功和失败数量
          const message = response.msg;
          const successMatch = message.match(/成功导入(\d+)条数据/);

          const successCount = successMatch ? parseInt(successMatch[1]) : 0;
          proxy.$modal.msgSuccess(`导入成功，共导入 ${successCount} 条博士信息`);
          getList(); // 刷新列表
        })
        .catch(error => {
          loading.close();
          proxy.$modal.msgError(error.msg || "导入失败，请稍后重试");
        });
  }).catch(() => {
    // 用户取消操作时也要重置加载状态
    importLoading.value = false;
  });
}

watch(previewDialogVisible, (visible) => {
  if (!visible && previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value);
    previewUrl.value = '';
  }
});

// 组件销毁时清除定时器
onUnmounted(() => {
  if (progressInterval) {
    clearInterval(progressInterval);
  }
});

// 初始加载列表数据
getList();
</script>

<style>
.scroll-to-bottom-btn {
  position: fixed;
  right: 30px;
  bottom: 50px;
  z-index: 999;
}

/* 进度弹窗样式 */
.progress-container {
  text-align: center;
  padding: 30px 0;
}

.progress-info {
  color: #606266;
  margin-top: 20px; /* 增加间距 */
}

.result-container {
  text-align: center;
  padding: 30px 0; /* 增加内边距 */
}

.result-icon {
  font-size: 60px; /* 增大图标 */
  margin-bottom: 25px;
  height: 70px;
  line-height: 70px;
}

.result-icon.success {
  color: #13ce66;
}

.result-icon.error {
  color: #ff4949;
}

.result-title {
  font-size: 22px; /* 增大标题 */
  font-weight: bold;
  margin-bottom: 25px;
}

.result-details {
  text-align: left;
  margin: 0 auto;
  max-width: 450px; /* 增加宽度 */
  background-color: #f5f7fa;
  padding: 20px; /* 增加内边距 */
  border-radius: 4px;
  font-size: 14px; /* 增大文字 */
}

.result-details p {
  margin: 10px 0; /* 增加段落间距 */
}

.failure-message {
  color: #ff4949;
  margin-top: 15px;
}

/* 特殊提示信息样式 */
.special-message {
  color: #409eff;
  margin-top: 15px;
  font-style: italic;
}
/* 添加失败学生列表样式 */
.failure-students {
  margin-top: 15px;
  padding: 15px;
  background-color: #fef0f0;
  border-radius: 4px;
  border-left: 4px solid #f56c6c;
}

.failed-students-list {
  max-height: 200px;
  overflow-y: auto;
  margin-top: 10px;
  padding-left: 20px;
}

.failed-students-list li {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
}

.button-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px; /* 设置固定间距 */
  align-items: center;
}

.button-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px; /* 设置固定间距 */
  align-items: center;
}

/* 确保所有按钮都有相同的宽度 */
.button-row .el-button {
  min-width: 120px;
  white-space: nowrap;
}

/* 针对长按钮的特殊处理 */
.button-row .el-button[icon="refresh"] {
  min-width: 160px;
}

/* 强制标签不换行 */
::v-deep .el-form-item__label {
  white-space: nowrap;
}

/* 增加表单项间距 */
::v-deep .el-form-item {
  margin-bottom: 15px;
}


</style>
